package cn.zyq.ykb.controller.mgt.login;


import cn.zyq.ykb.beans.sys.SysAdmin;
import cn.zyq.ykb.beans.sys.SysMenu;
import cn.zyq.ykb.service.sys.SysAdminService;
import cn.zyq.ykb.system.ry.vo.*;
import cn.zyq.ykb.service.sys.SysLoginService;
import cn.zyq.ykb.service.sys.SysMenuService;
import cn.zyq.ykb.service.sys.SysPermissionService;
import cn.zyq.ykb.system.ry.Constants;
import cn.zyq.ykb.system.ry.security.handle.AjaxResult;
import cn.zyq.ykb.system.ry.model.*;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@RequestMapping(value = "/mgt")
public class SysLoginController
{
    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysAdminService sysAdminService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Object login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = sysLoginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Object getInfo()
    {
        SysAdmin sysAdmin = SecurityUtils.getLoginUser().getSysAdmin();
        SysAdmin user = this.sysAdminService.selectUserById(sysAdmin.getSysAdminID());
        // 角色集合
        Set<String> roles = sysPermissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = sysPermissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public Object getRouters()
    {
        Integer userId = SecurityUtils.getSysAdminID();
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(userId);
        List<RouterVo> routerVos = sysMenuService.buildMenus(menus);
        return AjaxResult.success(routerVos);
    }
}
